package com.book.bookprojectapplication.login.activity;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.R.string;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.book.bookprojectapplication.R;
import com.tistory.whdghks913.croutonhelper.CroutonHelper;

import de.keyboardsurfer.android.widget.crouton.Style;

public class Findpassword extends Activity {
	Button backloginBtn;
	Button findpasswordBtn;
	EditText findpasswordText;
	CroutonHelper mHelper;

	HttpResponse response;
	String results;
	String password;

	JSONObject jArray;
	ArrayList<string> passworddata;

	String url = "http://192.168.123.182:8090/test/csjlookpassword.do";
	private String[] getJsonData = { "" };
	private String[] getJsonData1 = { "" };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.findpassword);

		backloginBtn = (Button) findViewById(R.id.backloginBtn);

		backloginBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent myIntent = new Intent(getApplicationContext(),
						LoginActivity.class);
				startActivity(myIntent);
			}
		});

		findpasswordBtn = (Button) findViewById(R.id.findpasswordBtn);
		findpasswordText = (EditText) findViewById(R.id.findpasswordText);
		mHelper = new CroutonHelper(this);
		mHelper.setDuration(1000);

		findpasswordBtn.setOnClickListener(new OnClickListener() {
			AlertDialog.Builder alert = new AlertDialog.Builder(
					Findpassword.this);

			@Override
			public void onClick(View v) {
				password = "?memail1=" + findpasswordText.getText().toString();
				new DownloadJSON().execute(url);

			}

		});
	}

	private class DownloadJSON extends AsyncTask<String, Void, Void> {
		@Override
		protected Void doInBackground(String... urls) {

			InputStream is = null;
			results = "";
			String passwordcheck = password;

			// Download JSON data from URL
			try {
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(urls[0] + password);
				response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();

				// Convert response to string

				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "utf-8"), 8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				results = sb.toString();
				System.out.println("result 값 : " + results);
				jArray = new JSONObject(results);

				JSONArray resarray = jArray.getJSONArray("mpassword");

				for (int i = 0; i < resarray.length(); i++) {
					jArray = resarray.getJSONObject(i);
					getJsonData[0] = jArray.getString("res");
					getJsonData1[0] = jArray.getString("mpassword");
				}
			} catch (Exception e) {
				Log.e("log_tag", "Error converting result " + e.toString());
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void args) {

			mHelper = new CroutonHelper(Findpassword.this);
			mHelper.setDuration(1000);
			System.out.println("onPosetExecute ()");

			if (findpasswordText.getText().toString().equals("")) {
				mHelper.setStyle(Style.ALERT);
				mHelper.setText("이메일을 입력해주세요");
				mHelper.show();
			} else if (getJsonData[0].equals("no")) {
				mHelper.setStyle(Style.ALERT);
				mHelper.setText("존재하지않는 이메일입니다. 이메일를 확인해주세요");
				mHelper.show();

			} else if (getJsonData[0].equals("ok")) {
				mHelper.setStyle(Style.CONFIRM);
				mHelper.setText(findpasswordText.getText()
						+ "로 이메일을 보냈습니다. 확인해주세요");
				mHelper.show();

				String fromEmail = "chaesj818@gmail.com";
				String fromPassword = "cj000909";
				String toEmails = findpasswordText.getText().toString();
				List<String> toEmailList = Arrays.asList(toEmails
						.split("\\s*,\\s*"));
				Log.i("SendMailActivity", "To List: " + toEmailList);
				String emailSubject = "[책,보다너]이메일안내입니다.";
				String emailBody = "당신의 비밀번호는 " + getJsonData1[0] + "입니다";

				new SendMailTask(Findpassword.this).execute(fromEmail,
						fromPassword, toEmailList, emailSubject, emailBody);

			}
		}

	}
}
